﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CashFlow.Repository;
using CashFlow.Entities;
using System.Diagnostics.Contracts;
using CashFlow.Common;
using Microsoft.WindowsAzure;

namespace CashFlow.AzureRepository
{
	public class AzureTenantRepository : AzureRepositoryBase, ITenantRepository
	{
		#region Constructors
		/// <summary>
		/// Initializes a new instance of the <see cref="T:AzureRepositoryBase"/> class.
		/// </summary>
		public AzureTenantRepository()
		{
		}

		public AzureTenantRepository(string tenantId)	: base(tenantId)
		{
		}

		#endregion

		public Tenant GetById()
		{
			Tenant entity = null;
			var dbEntity = GetDbEntityById(tenantId);
			//TODO: vvs p3 this check can be moved to the base class (it will be done for all tables).
			if (dbEntity != null)
			{
				entity = (Tenant)dbEntity;
			}

			return entity;
		}

		private TenantAzure GetDbEntityById(string id)
		{
			var dbEntity = GetByKeys<TenantAzure>(Constants.TableNames.Tenants, id, string.Empty);
			return dbEntity;
		}

		public void UpdateBalance(Tenant tenant)
		{
			Contract.Requires(tenant != null, "tenant cannot be null.");
			Contract.Requires(!string.IsNullOrEmpty(tenant.Id), "tenant id cannot be null.");

			var existingTenant = GetDbEntityById(tenant.Id);
			existingTenant.InitialBalanceAmount = tenant.InitialBalanceAmount;
			existingTenant.InitialBalanceDate = tenant.InitialBalanceDate;

			Update(Constants.TableNames.Tenants, existingTenant, false);
		}

		public void Create(Tenant tenant)
		{
			Contract.Requires(tenant != null, "tenant cannot be null.");
			Contract.Requires(!string.IsNullOrEmpty(tenant.Id), "tenant id cannot be null.");

			//TODO: vvs p2 save with retry.
			var azureEntity = (TenantAzure)tenant;
			db.AddObject(Constants.TableNames.Tenants, azureEntity);
			db.SaveChanges();
		}
	}
}
